package week4;

import jsjf.exceptions.ElementNotFoundException;
import jsjf.exceptions.EmptyCollectionException;

import java.util.Iterator;

public class ArrayList<T> implements ListADT<T>, Iterable<T> {
    private final static int DEFAULT_CAPACITY = 100;
    private final static int NOT_FOUND = -1;

    protected int rear;
    protected T[] list;
    protected int modCount;

    // 创建一个默认容量的空列表
    public ArrayList()
    {
        this(DEFAULT_CAPACITY);
    }

    // 创建一个特定容量的空列表
    public ArrayList(int initialCapacity)
    {
        rear = 0;
        list = (T[])(new Object[initialCapacity]);
        modCount = 0;
    }

    // 删除并且返回特定元素
    public T remove(T element)
    {
        T result;
        int index = find(element);

        if (index == NOT_FOUND) {
            throw new ElementNotFoundException("ArrayList");
        }
        result = list[index];
        rear--;

        // 移动适当的元素
        for (int scan=index; scan < rear; scan++) {
            list[scan] = list[scan + 1];
        }
        list[rear] = null;
        modCount++;

        return result;
    }

    public T removeFirst()
    {
        T result;
        result = list[0];
        rear--;

        for (int scan= 0; scan < rear; scan++) {
            list[scan] = list[scan + 1];
        }
        list[rear] = null;
        modCount++;

        return result;
    }

    public T removeLast()
    {
        T result;
        result = list[list.length - 1];
        rear--;

        list[rear] = null;
        modCount++;

        return result;
    }

    public T first() throws EmptyCollectionException
    {
        if (isEmpty())
        {
            throw new EmptyCollectionException("ArrayList");
        }

        return list[0];
    }

    public T last() throws EmptyCollectionException
    {
        if (isEmpty())
        {
            throw new EmptyCollectionException("ArrayList");
        }

        return list[rear - 1];
    }


    // 返回元素的数组索引，如果没找到返回NOT_FOUND
    private int find(T target)
    {
        int scan = 0;
        int result = NOT_FOUND;

        if (!isEmpty()) {
            while (result == NOT_FOUND && scan < rear) {
                if (target.equals(list[scan])) {
                    result = scan;
                } else {
                    scan++;
                }
            }
        }
        return result;
    }

    // 如果有特定元素就返回true
    public boolean contains(T target)
    {
        return (find(target) != NOT_FOUND);
    }

    public int size()
    {
        return rear;
    }


    public String toString()
    {
        String result = "";
        for (int a = 0; a<rear;a++)
        {
            result += list[a] + " ";
        }
        return result;
    }

    @Override
    public Iterator<T> iterator() {
        return null;
    }

    public boolean isEmpty() {
        return rear == 0;
    }
}
